const http = require('http');
const fs = require('fs');
const queryString = require('querystring')
const path = require('path')

const server = http.createServer((req, res) => {

    // 静态资源处理
    if (/.html$/.test(req.url)) {
        let filePath = __dirname + '/' + req.url
        res.writeHead(200);
        fs.createReadStream(filePath).pipe(res)
    } else {
        // getFileList
        // download?filename=xxx

        // 文件列表接口
        if (req.url.startsWith('/getFileList') && req.method === 'GET') {
            let dirPath = path.join(__dirname, '/upload')
            fs.readdir(dirPath, (err, data) => {
                if (!err) {
                    console.log(data)
                    let result = {
                        success: true,
                        msg: '',
                        data: data
                    }
                    res.statusCode = 200
                    res.end(JSON.stringify(result));
                }
            })
        } else if (req.url.startsWith('/download') && req.method === 'GET') {
            // 下载文件
            let body = req.url.split('?')[1];
            body = queryString.parse(body);
            console.log(body.filename);

            let filePath = path.join(__dirname, '/upload', body.filename);
            let r = fs.createReadStream(filePath);
            
            let fileState = fs.statSync(filePath);

            // 文件描述
            res.setHeader('Content-Disposition', `attachment; filename=${body.filename}`);
            // 设置返回内容为二进制
            res.setHeader('content-type', 'application/octet-stream');
            // 文件大小
            res.setHeader('Content-Length', fileState.size);

            res.statusCode = 200;
            r.pipe(res);
        }
    }
})

server.listen(3001, () => {
    console.log('server is runing localhost:3001')
})
